package com.example.server

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import java.io.*
import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.util.concurrent.ConcurrentLinkedQueue


var q = ConcurrentLinkedQueue<Long>()
var last_update = System.currentTimeMillis()

class thrC : Thread() {
    lateinit var upper: MainActivity

    override fun run() {
        while (true) {
            last_update = System.currentTimeMillis()
            upper.runOnUiThread({ upper.show() })
            var g: Long = 1000
            if (q.size > 0) {
                var t = q.poll()!!
                println(t)
                g = t + 1000 - System.currentTimeMillis()
                if (g < 0)
                    g = 0
            }
            Thread.sleep(g)
        }
    }

}

var has_start = false
var xx = thrC()
var t_num = 9

class MainActivity : AppCompatActivity() {
    fun save_state(idx: Int, ty: Int, content: Long) {
        var path: File = baseContext.filesDir
        var file: File = File(path, idx.toString() + "state" + ty.toString())
        var f = FileOutputStream(file)
        var bb = ByteBuffer.allocate(100)
        bb.putLong(content)
        f.write(bb.array())
        f.close()
    }

    fun read_state(idx: Int, ty: Int): Long {
        var path: File = baseContext.filesDir
        var file: File = File(path, idx.toString() + "state" + ty.toString())
        var f = FileInputStream(file)
        val b = ByteArray(100)
        f.read(b, 0, 100)
        f.close()
        var bb = ByteBuffer.wrap(b)
        var l = bb.getLong()
        return l
    }

    fun saveDes(a: Int, b: String) {
        var path: File = baseContext.filesDir
        var file: File = File(path, "des" + a.toString())
        var f = FileOutputStream(file)
        f.write(b.toByteArray(Charset.defaultCharset()))
        f.close()
    }

    fun readDes(a: Int): String {
        try {
            var path2: File = baseContext.filesDir
            var file2: File = File(path2, "des" + a.toString())
            var f2 = FileInputStream(file2)
            f2.close()
        } catch (e: Exception) {
            return "none"
        }

        var path: File = baseContext.filesDir
        var file: File = File(path, "des" + a.toString())
        var f = FileInputStream(file)

        val b = ByteArray(100)
        var n = f.read(b, 0, 100)
        f.close()
        return b.slice(0..<n).toByteArray().toString(Charset.defaultCharset())
    }

    fun iniDes() {
        for (i in 1..t_num) {
            var s = readDes(i)
            val id = resources.getIdentifier("text1_" + i.toString() + "x", "id", packageName)
            findViewById<EditText>(id).setText(s)
        }
    }

    fun onPlay(a: Int) {
        var state = read_state(a, 0)
        var start_num = read_state(a, 1)
        var total = read_state(a, 2)

        if (state.toInt() == 0) {
            save_state(a, 0, 1)
            save_state(a, 1, System.currentTimeMillis())
            if (total / 1000 == (1000 + last_update - System.currentTimeMillis() + total) / 1000)
                q.add(System.currentTimeMillis())
            return
        }
        var gap = System.currentTimeMillis() - start_num
        total += gap
        save_state(a, 0, 0)
        save_state(a, 2, total)
    }

    fun onClear(a: Int) {
        save_state(a, 0, 0)
        save_state(a, 1, 0)
        save_state(a, 2, 0)
    }

    fun check(a: Int) {
        try {
            var state = read_state(a, 0)
            var start_num = read_state(a, 1)
            var total = read_state(a, 2)
            if (state.toInt() == 0) {
                val id = resources.getIdentifier("btn2_" + a.toString() + "x", "id", packageName)
                if (findViewById<Button>(id).text != "|>")
                    findViewById<Button>(id).text = "|>"
                val id2 = resources.getIdentifier("text2_" + a.toString() + "x", "id", packageName)
                if (findViewById<EditText>(id2).text.toString() != (total / 1000).toString())
                    findViewById<EditText>(id2).setText((total / 1000).toString())
                return
            }
            val id = resources.getIdentifier("btn2_" + a.toString() + "x", "id", packageName)
            if (findViewById<Button>(id).text != "||")
                findViewById<Button>(id).text = "||"
            var gap = System.currentTimeMillis() - start_num + total
            val id2 = resources.getIdentifier("text2_" + a.toString() + "x", "id", packageName)
            if (findViewById<EditText>(id2).text.toString() != (gap / 1000).toString())
                findViewById<EditText>(id2).setText((gap / 1000).toString())
        } catch (e: Exception) {
            onClear(a)
        }
    }

    fun onDes(i: Int) {
        val id2 = resources.getIdentifier("text1_" + i.toString() + "x", "id", packageName)
        saveDes(i, findViewById<EditText>(id2).text.toString())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        println("start")
        this.getSupportActionBar()?.hide();
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        xx.upper = this
        for (i in 1..t_num) {
            val id = resources.getIdentifier("btn2_" + i.toString() + "x", "id", packageName)
            findViewById<Button>(id).setOnClickListener {
                onDes(i)
                onPlay(i)
                check(i)

            }
        }
        for (i in 1..t_num) {
            val id = resources.getIdentifier("btn1_" + i.toString() + "x", "id", packageName)
            findViewById<Button>(id).setOnClickListener {
                onDes(i)
                onClear(i)
                check(i)
            }
        }

        if (has_start) {
            println("has started")
            return
        }

        has_start = true
        xx.isDaemon = true
        xx.start()
        iniDes()
    }


    fun show() {
        for (i in 1..t_num) {
            check(i)
        }
    }
}
